﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZHDJ.Core;
using ZHDJ.Core.Util;

namespace ZHDJ.Data.Models.Common
{
    /// <summary>
    /// 待办
    /// </summary>
    public class PartyTask : EntityBase
    {
        #region 字段属性
        /// <summary>
        /// 关联ID
        /// </summary>
        public string RelationID { get; set; }

        /// <summary>
        /// 待办类型
        /// </summary>
        public string Category { get; set; }

        /// <summary>
        /// 待办状态1待办  2:：已办，，3 取消，4删除
        /// </summary>
        public string TaskType { get; set; }

        /// <summary>
        /// 待办标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 发送人
        /// </summary>
        public string FromUser { get; set; }
        /// <summary>
        ///接收人/组织
        /// </summary>
        public string ToUser { get; set; }

        /// <summary>
        /// 待办地址
        /// </summary>
        public string TaskUrl { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? CreateTime { get; set; }

        /// <summary>
        /// 处理人
        /// </summary>
        public string Handler { get; set; }
       /// <summary>
        /// 处理时间
        /// </summary>
        public DateTime? HandlerTime { get; set; }

        /// <summary>
        /// 人/组织待办
        /// </summary>
        public string TaskSpecie { get; set; }

        /// <summary>
        /// 数据来源（保留）
        /// </summary>
        public string Source { get; set; }
        #endregion

        #region 查询管理

        public static DataSet GetGridData(int pageIndex, int pageSize, string category, string searchKey, SysEnum.TaskType taskType,  SysEnum.TaskSpecie taskSpecie,string toUserOrBranch="")
        {
            List<MySqlParameter> parameters = new List<MySqlParameter>()
            {
                new MySqlParameter(){DbType = DbType.Int32,ParameterName = "Begin",Value = (pageIndex)*pageSize},
                new MySqlParameter(){DbType = DbType.Int32,ParameterName = "PageSize",Value = pageSize},
                new MySqlParameter(){DbType = DbType.String,ParameterName = "TaskSpecie",Value = taskSpecie.ToString()},
                new MySqlParameter(){DbType = DbType.String,ParameterName = "Module",Value = SysDataDictionary.TaskCategory},
                new MySqlParameter(){DbType = DbType.String,ParameterName = "taskType",Value = (int)taskType}
            };
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select SQL_CALC_FOUND_ROWS  data.*,m.UserName FromUserName,m2.UserName HandlerUserName,d.DDicMemberName as CategoryName
                        from tblPartyTask data
                        left join tblPartyOrgMember m on(data.FromUser=m.LoginID)
                        left join tblPartyOrgMember m2 on(data.Handler=m2.LoginID)
                       left join tbldatadictionary d on (d.DDicType=?Module and data.Category=d.DDicMember)
                        where TaskSpecie=?TaskSpecie and taskType=?taskType ");
            if (!string.IsNullOrEmpty(searchKey))
            {
                sb.Append(" and (m.UserName like ?key  or data.Title like ?key  )");
                parameters.Add(
                    new MySqlParameter() { DbType = DbType.String, ParameterName = "key", Value = string.Format("%{0}%", searchKey) });
            }
            if (!string.IsNullOrEmpty(category))
            {
                sb.Append(" and data.category=?category ");
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "category", Value = category });
            }

            if (!string.IsNullOrEmpty(toUserOrBranch))
            {
                sb.Append(" and data.ToUser=?ToUser ");
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "ToUser", Value = toUserOrBranch });
            }
            sb.Append(" order by data.TaskType,data.CreateTime desc LIMIT ?Begin ,?PageSize;SELECT FOUND_ROWS();");
            return MySqlHelper.ExecuteDataSet(sb.ToString(), parameters.ToArray());
        }

        /// <summary>
        /// 添加待办
        /// </summary>
        /// <param name="relationID"></param>
        /// <param name="title"></param>
        /// <param name="category"></param>
        /// <param name="fromUser"></param>
        /// <param name="toUsers"></param>
        /// <param name="taskUrl"></param>
        /// <param name="taskSpecie"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool AddTask(string relationID, string title, string category, string fromUser, string[] toUsers, string taskUrl, string taskSpecie, string source = "本组织")
        {
            StringBuilder sbSql = new StringBuilder();
            List<MySqlParameter> parameters = new List<MySqlParameter>();
            string strSql = @"INSERT INTO tblPartyTask (ID, RelationID, Category, TaskType, Title, FromUser, ToUser, TaskUrl, CreateTime,TaskSpecie,Source)
                                    VALUES (?TaskID{0}, ?RelationID, ?Category, ?TaskType, ?Title, ?FromUser, ?ToUser{0}, ?TaskUrl{0}, NOW(), ?TaskSpecie{0}, ?Source);";


            for (int i = 0; i < toUsers.Length; i++)
            {
                string taskID = StringHelper.NewID;
                string tmpTaskUrl = "";
                sbSql.AppendFormat(strSql, i);
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = string.Format("ToUser{0}", i), Value = string.IsNullOrEmpty(toUsers[i]) ? "" : toUsers[i] });
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = string.Format("TaskID{0}", i), Value = taskID });

                if (taskUrl.IndexOf("?") > 0)
                    tmpTaskUrl = taskUrl + "&TaskID=" + taskID;
                else
                    tmpTaskUrl = taskUrl + "?TaskID=" + taskID;
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = string.Format("TaskUrl{0}", i), Value = tmpTaskUrl });
                parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = string.Format("TaskSpecie{0}", i), Value = taskSpecie });
            }

            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "RelationID", Value = relationID });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "Category", Value = category });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "TaskType", Value = "1" });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "Title", Value = title });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "FromUser", Value = fromUser });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "Source", Value = source });

            if (sbSql.Length > 0)
            {
                return MySqlHelper.ExecuteNonQuery(sbSql.ToString(), parameters.ToArray()) > 0;
            }
            else
            {
                return false;
            }
        }

        public static string GetTaskTypeByTakeID(string taskID)
        {
            string sql = "select TaskType from tblPartyTask where ID=?TaskID";
            List<MySqlParameter> parameters = new List<MySqlParameter>();

            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "TaskID", Value = taskID });
            object o = MySqlHelper.ExecuteScalar(sql, parameters.ToArray());
            return o != null ? o.ToString() : "";
        }



        public static string GetTaskToUser(string taskID)
        {
            if (string.IsNullOrEmpty(taskID))
                return string.Empty;

            List<MySqlParameter> parameters = new List<MySqlParameter>();
            string sql = "select ToUser from tblPartyTask where ID=?TaskID";
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "TaskID", Value = taskID });
            return Convert.ToString(MySqlHelper.ExecuteScalar(sql, parameters.ToArray()));
        }

        
        /// <summary>
        /// 获取用户当前步骤
        /// </summary>
        /// <param name="LoginID"></param>
        /// <returns></returns>
        public static string GetCurrentStepIDByLoginID(string loginID)
        {
            string currentStepID = string.Empty;
            List<MySqlParameter> parameters = new List<MySqlParameter>();
            string sql = @"SELECT CurrentStepID FROM tblPartyJoinLinkExample WHERE Status=0 
AND AppllicationID=(SELECT AppllicationID FROM tblPartyJoinApplycation WHERE LoginID=?LoginID AND Status=1)
";
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "LoginID", Value = loginID });
            object obj = MySqlHelper.ExecuteScalar(sql, parameters.ToArray());
            if (obj != null)
            {
                currentStepID = obj.ToString();
            }
            return currentStepID;
        }

        /// <summary>
        /// 回滚到指定步骤
        /// </summary>
        /// <param name="backToStepID">指定步骤</param>
        /// <param name="applyBy">申请人</param>
        /// <param name="branchID">申请进入的组织(为空时组织不变）</param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static bool BackToStep(string backToStepID, string applyBy, string branchID, string handler = "admin")
        {
            DataTable dt = PartyOrg.GetBranchAdmin(branchID);
            List<MySqlParameter> parameters = new List<MySqlParameter>();
            List<string> listLoginID = new List<string>();
            List<string> listUserName = new List<string>();

            foreach (DataRow item in dt.Rows)
            {
                listLoginID.Add(Convert.ToString(item["LoginID"]));
                listUserName.Add(Convert.ToString(item["Username"]));
            }
            var ToDoHandleUserID = string.Join(",", listLoginID);
            var ToDoHandleUserName = string.Join(",", listUserName);

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(@"
--事务
begin try
begin tran TranBacktostep
--declare @BackToStepID varchar(32)
--declare @ApplyBy varchar(32)
--declare @BranchID varchar(32)
--declare @Handler  varchar(32)

--set @BackToStepID='JoinStep6'
--set @BranchID='1f84a78b81844259b68e373fa4f5855b'
--set @ApplyBy='xian001'
--set @Handler='admin'

declare @TempBranchID varchar(32)
declare @BackToStandID varchar(32)
declare @BackToorderno int
declare @BackToAppllicationID varchar(32)

--查找退回到的步骤信息

select top 1 
@BackToAppllicationID=AppllicationID,@TempBranchID=BranchID from  [dbo].[tblPartyJoinApplycation]  where LoginID=@ApplyBy and Status=1  order by CreateTime desc

select @BackToStandID=StandID, @BackToorderno=orderno
from [tblPartyJoinLinkExample] where CurrentStepID=@BackToStepID and AppllicationID=@BackToAppllicationID

if(@BranchID<>'')
  set @TempBranchID=@BranchID

--清除待办
UPDATE dbo.tblPartyTask SET TaskType = 5,Handler = @Handler WHERE RelationID  in 
(select StandID from [tblPartyJoinLinkExample] where orderno>@BackToorderno and [AppllicationID]=@BackToAppllicationID)
--还原上一步待办
UPDATE dbo.tblPartyTask SET TaskType = 1,Handler = @Handler,CreateTime=getdate() WHERE RelationID=@BackToStandID
UPDATE dbo.tblPartyTask SET ToUser=@TempBranchID WHERE RelationID =@BackToStandID and TaskSpecie='Branch'

--撤销步骤
delete tblPartyJoinLinkExample where StandID in 
(select StandID from [tblPartyJoinLinkExample] where orderno>@BackToorderno and [AppllicationID]=@BackToAppllicationID) 

--删除子流程（如果有）
delete tblPartyJoinChildFlow where StandID in 
(select StandID from [tblPartyJoinLinkExample] where orderno>@BackToorderno and [AppllicationID]=@BackToAppllicationID)
--更新回到步骤状态
update tblPartyJoinLinkExample set Status='0', ToDoHandleUserName=@ToDoHandleUserName,ToDoHandleUserID=@ToDoHandleUserID where StandID in(
select Top 1 StandID from tblPartyJoinLinkExample 
where  AppllicationID =@BackToAppllicationID
order by OrderNo desc)
--如果回到第六步，把 原培养联系人设置为历史状态
if @BackToStepID='JoinStep6'
begin
     update tblpartyJoinContact set isolddata=1 where AppllicationID=@BackToAppllicationID 
end

--更新申请单的组织
update [tblPartyJoinApplycation] set [BranchID]=@TempBranchID  where AppllicationID=@BackToAppllicationID
COMMIT TRAN TranBacktostep

end try 
begin catch 
     ROLLBACK TRAN TranBacktostep
end catch 
 ");
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "BackToStepID", Value = backToStepID });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "ApplyBy", Value = applyBy });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "BranchID", Value = branchID });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "Handler", Value = handler });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "ToDoHandleUserName", Value = ToDoHandleUserName });
            parameters.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "ToDoHandleUserID", Value = ToDoHandleUserID });

            return MySqlHelper.ExecuteNonQuery(sbSql.ToString(), parameters.ToArray()) > 0;
        }
        #endregion
    }
}
